<template>
	<view class="container">
		<view class="calculator-form">
			<view class="form-title">
				<text>生猛羽毛球活动费用计算器</text>
			</view>

			<!-- Participants Section -->
			<view class="section">
				<text class="section-title">参与者管理</text>
				<view v-if="errorMessage" class="error-message">
					{{ errorMessage }}
				</view>
				<!-- Add column labels -->
				<view class="column-labels">
					<text class="name-label">姓名</text>
					<view class="payment-labels">
						<text class="payment-label">场地费垫付</text>
						<text class="payment-label">球费垫付</text>
					</view>
					<text class="action-label">操作</text>
				</view>
				<view class="participants-list">
					<view v-for="(participant, index) in participants" :key="index" class="participant-item">
						<input type="text" v-model="participant.name" placeholder="参与者姓名" class="name-input"
							@input="validateParticipantName($event, index)" />
						<view class="payment-inputs">
							<input type="number" v-model="participant.courtFee" placeholder="垫付场地费"
								class="payment-input" @input="($event) => validateFee($event, index, 'courtFee')" />
							<input type="number" v-model="participant.shuttleFee" placeholder="垫付球费"
								class="payment-input" @input="($event) => validateFee($event, index, 'shuttleFee')" />
						</view>
						<button @click="removeParticipant(index)" class="remove-btn">删除</button>
					</view>
				</view>
				<button @click="showAddParticipant" class="add-participant-btn">
					<text class="add-icon">+</text> 添加参与者
				</button>
			</view>

			<!-- Add the modal for adding new participant -->
			<view v-if="showAddModal" class="modal-overlay">
				<view class="modal-content">
					<view class="modal-header">
						<text class="modal-title">添加参与者</text>
					</view>
					<view class="participant-form">
						<input type="text" v-model="currentParticipant.name" placeholder="参与者姓名" class="modal-input"
							@input="handleCurrentParticipantName" />
						<input type="number" v-model="currentParticipant.courtFee" placeholder="垫付场地费"
							class="modal-input" @input="validateCurrentFee('courtFee')" />
						<input type="number" v-model="currentParticipant.shuttleFee" placeholder="垫付球费"
							class="modal-input" @input="validateCurrentFee('shuttleFee')" />
					</view>
					<view class="modal-footer">
						<button @click="cancelAdd" class="modal-btn cancel-btn">取消</button>
						<button @click="addParticipant" class="modal-btn confirm-btn" :disabled="!canAddParticipant"
							:class="{ 'btn-disabled': !canAddParticipant }">确认添加</button>
					</view>
				</view>
			</view>

			<!-- Time Periods Section -->
			<view class="section" v-if="settlementType === 'detailed'">
				<text class="section-title">时间段管理</text>
				<!-- Add column labels -->
				<view class="period-column-labels">
					<text class="period-number-label">时间段</text>
					<view class="period-fee-labels">
						<text class="period-fee-label">场地费</text>
						<text class="period-fee-label">球费</text>
					</view>
					<text class="period-action-label">操作</text>
				</view>
				<view class="time-periods-list">
					<view v-for="(period, periodIndex) in timePeriods" :key="periodIndex" class="time-period-item">
						<view class="period-fees">
							<text class="period-title" style="line-height: 35px;">{{ period.name }}</text>
							<input type="number" v-model="period.courtFee" placeholder="场地费" class="fee-input"
								@input="validatePeriodFee($event, periodIndex, 'courtFee')" />
							<input type="number" v-model="period.shuttleFee" placeholder="球费" class="fee-input"
								@input="validatePeriodFee($event, periodIndex, 'shuttleFee')" />
							<button @click="removePeriod(periodIndex)" class="remove-btn">删除</button>
						</view>
						<view class="period-participants">
							<view class="participant-checkboxes" style="display: flex; flex-wrap: wrap; gap: 10rpx;">
								<view v-for="(participant, participantIndex) in participants" :key="participantIndex"
									class="participant-checkbox">
									<view class="participant-control">
										<view class="participant-main-checkbox">
											<checkbox :checked="period.selectedParticipants[participantIndex]"
												@click="toggleParticipant(periodIndex, participantIndex)" />
											<text>{{ participant.name }}</text>
										</view>
										<view v-if="period.selectedParticipants[participantIndex]"
											class="half-fee-switch">
											<switch :checked="period.shuttleFeeHalved[participantIndex]"
												@change="toggleShuttleFeeHalved(periodIndex, participantIndex)"
												style="transform: scale(0.7);" color="#007AFF" />
											<text class="switch-label">球费减半</text>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
				<button @click="showAddPeriod" class="add-participant-btn">
					<text class="add-icon">+</text> 添加时间段
				</button>

				<!-- Add the modal for adding new time period -->
				<view v-if="showAddPeriodModal" class="modal-overlay">
					<view class="modal-content">
						<view class="modal-header">
							<text class="modal-title">添加时间段</text>
						</view>
						<view class="participant-form">
							<input type="text" v-model="currentPeriod.name" placeholder="时间段名称（选填）"
								class="modal-input" />
							<input type="number" v-model="currentPeriod.courtFee" placeholder="场地费" class="modal-input"
								@input="validateCurrentPeriodFee('courtFee')" />
							<input type="number" v-model="currentPeriod.shuttleFee" placeholder="球费" class="modal-input"
								@input="validateCurrentPeriodFee('shuttleFee')" />
						</view>
						<view class="modal-footer">
							<button @click="cancelAddPeriod" class="modal-btn cancel-btn">取消</button>
							<button @click="addPeriod" class="modal-btn confirm-btn" :disabled="!canAddPeriod"
								:class="{ 'btn-disabled': !canAddPeriod }">确认添加</button>
						</view>
					</view>
				</view>
			</view>

			<!-- Settlement Section -->
			<view class="section">
				<text class="section-title">结算</text>
				<view class="settlement-type">
					<radio-group @change="handleSettlementTypeChange" class="settlement-radio-group">
						<label class="radio-label">
							<radio value="simple" :checked="settlementType === 'simple'" />简算
						</label>
						<label class="radio-label">
							<radio value="detailed" :checked="settlementType === 'detailed'" />详细结算
						</label>
					</radio-group>
					<view class="settlement-info">
						<text class="info-icon">ℹ</text>
						<text class="info-text">{{ settlementTypeInfo }}</text>
					</view>
				</view>

				<!-- Add this new section for simple mode shuttle fee halving -->
				<view v-if="settlementType === 'simple' && participants.length > 0" class="simple-fee-controls">
					<text class="simple-fee-title">选择球费减半的参与者：</text>
					<view class="simple-participants-list">
						<view v-for="(participant, index) in participants" :key="index" class="simple-participant-item">
							<switch :checked="simpleShuttleFeeHalved[index]"
								@change="toggleSimpleShuttleFeeHalved(index)" style="transform: scale(0.7);"
								color="#007AFF" />
							<text class="simple-participant-name">{{ participant.name }}</text>
						</view>
					</view>
				</view>

				<button @click="validateAndSettle" class="settle-btn" :disabled="!canSettle"
					:class="{ 'settle-btn-disabled': !canSettle }">结算费用</button>

				<!-- Add remarks input -->
				<view class="remarks-section">
					<text class="remarks-label">备注信息</text>
					<textarea v-model="remarks" placeholder="添加备注信息（选填）" class="remarks-input" />
				</view>
			</view>

			<!-- Settlement Results Section -->
			<view v-if="settlementResults" class="settlement-section">
				<text class="section-title">结算结果</text>
				<view class="summary-content">
					<text>总场地费: ¥{{ Number(totalCourtFee).toFixed(2) }}</text>
					<text>总球费: ¥{{ Number(totalShuttleFee).toFixed(2) }}</text>
					<text>总费用: ¥{{ Number(totalCost).toFixed(2) }}</text>
					<text>总垫付: ¥{{ Number(totalPaidAmount).toFixed(2) }}</text>
				</view>
				<view class="settlement-results">
					<view v-for="(summary, name) in settlementResults" :key="name" class="participant-summary">
						<text>{{ name }}:
							垫付 ¥{{ Number(summary.paid).toFixed(2) }} (场地费:¥{{ Number(summary.courtFee).toFixed(2) }},
							球费:¥{{ Number(summary.shuttleFee).toFixed(2) }})
							应付 ¥{{ Number(summary.shouldPay).toFixed(2) }}
							{{ summary.balance > 0 ? '需退还' : '需补交' }} ¥{{ Math.abs(summary.balance).toFixed(2) }}
						</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			participants: [],
			errorMessage: '',
			hasError: false,
			showAddModal: false,
			showAddPeriodModal: false,
			currentParticipant: {
				name: '',
				courtFee: '',
				shuttleFee: ''
			},
			currentPeriod: {
				name: '',
				courtFee: '',
				shuttleFee: ''
			},
			timePeriods: [],
			settlementResults: null,
			settlementType: 'simple',
			simpleShuttleFeeHalved: [],
			remarks: '' // 添加备注字段
		}
	},
	computed: {
		totalCourtFee() {

			return this.timePeriods.reduce((sum, period) => {
				const fee = period.courtFee === '' ? 0 : Number(period.courtFee)
				const participantCount = period.selectedParticipants.filter(Boolean).length
				return sum + (participantCount > 0 ? fee : 0)
			}, 0)
		},
		totalShuttleFee() {
			return this.timePeriods.reduce((sum, period) => {
				const fee = period.shuttleFee === '' ? 0 : Number(period.shuttleFee)
				const participantCount = period.selectedParticipants.filter(Boolean).length
				return sum + (participantCount > 0 ? fee : 0)
			}, 0)
		},
		totalCost() {
			return this.totalCourtFee + this.totalShuttleFee
		},
		participantsSummary() {
			const summary = {}

			// 初始化每个参与者的汇总信息
			this.participants.forEach((participant, participantIndex) => {
				if (participant.name) {
					summary[participant.name] = {
						courtFee: participant.courtFee === '' ? 0 : Number(participant.courtFee), // 垫付的场地费
						shuttleFee: participant.shuttleFee === '' ? 0 : Number(participant.shuttleFee), // 垫付的球费
						paid: (participant.courtFee === '' ? 0 : Number(participant.courtFee)) +
							(participant.shuttleFee === '' ? 0 : Number(participant.shuttleFee)), // 总垫付
						shouldPay: 0, // 应付金额
						balance: 0 // 最终余额（负数表示需要补交，正数表示需要退还）
					}

					// 计算每个时间段中该参与者应付的费用
					this.timePeriods.forEach(period => {
						if (period.selectedParticipants[participantIndex]) {
							const participantCount = period.selectedParticipants.filter(Boolean).length
							if (participantCount > 0) {
								const courtFeeShare = Number(period.courtFee || 0) / participantCount
								const shuttleFeeShare = Number(period.shuttleFee || 0) / participantCount

								summary[participant.name].shouldPay += courtFeeShare + shuttleFeeShare
							}
						}
					})

					// 计算最终余额：垫付金额 - 应付金额
					summary[participant.name].balance =
						summary[participant.name].paid - summary[participant.name].shouldPay
				}
			})

			return summary
		},
		canAddParticipant() {
			// Check if name is not empty and unique
			const nameExists = this.participants.some(p =>
				p.name.trim().toLowerCase() === this.currentParticipant.name.trim().toLowerCase()
			)
			if (nameExists || !this.currentParticipant.name.trim()) {
				return false
			}

			// Validate fees
			const courtFee = Number(this.currentParticipant.courtFee || 0)
			const shuttleFee = Number(this.currentParticipant.shuttleFee || 0)

			return !isNaN(courtFee) && !isNaN(shuttleFee) && courtFee >= 0 && shuttleFee >= 0 && !this.hasError
		},
		totalPaidAmount() {
			return this.participants.reduce((sum, p) => {
				return sum +
					(p.courtFee === '' ? 0 : Number(p.courtFee)) +
					(p.shuttleFee === '' ? 0 : Number(p.shuttleFee))
			}, 0)
		},
		canSettle() {
			if (this.settlementType === 'simple') {
				return this.participants.length > 0;
			}
			return this.participants.length > 0 && this.timePeriods.length > 0
		},
		canAddPeriod() {
			const courtFee = Number(this.currentPeriod.courtFee || 0)
			const shuttleFee = Number(this.currentPeriod.shuttleFee || 0)

			return !isNaN(courtFee) && !isNaN(shuttleFee) &&
				courtFee >= 0 && shuttleFee >= 0 && !this.hasError
		},
		settlementTypeInfo() {
			return this.settlementType === 'simple'
				? '简算模式：按总费用均分，不考虑时间段参与情况'
				: '详细结算模式：根据每个时间段的参与情况精确计算费用分摊';
		}
	},
	watch: {
		participants: {
			handler(newParticipants) {
				// Ensure simpleShuttleFeeHalved array matches participants length
				while (this.simpleShuttleFeeHalved.length < newParticipants.length) {
					this.simpleShuttleFeeHalved.push(false)
				}
				// Trim extra elements if participants were removed
				if (this.simpleShuttleFeeHalved.length > newParticipants.length) {
					this.simpleShuttleFeeHalved.length = newParticipants.length
				}
			},
			immediate: true
		}
	},
	methods: {
		toggleSimpleShuttleFeeHalved(index) {
			this.$set(this.simpleShuttleFeeHalved, index, !this.simpleShuttleFeeHalved[index])
		},
		showAddParticipant() {
			this.showAddModal = true;
			this.currentParticipant = {
				name: '',
				courtFee: '',
				shuttleFee: ''
			};
			this.errorMessage = '';
		},

		cancelAdd() {
			this.showAddModal = false;
			this.currentParticipant = {
				name: '',
				courtFee: '',
				shuttleFee: ''
			};
			this.errorMessage = '';
		},

		addParticipant() {
			if (!this.canAddParticipant) {
				return
			}

			// Check for duplicate name
			const nameExists = this.participants.some(p =>
				p.name.trim().toLowerCase() === this.currentParticipant.name.trim().toLowerCase()
			)
			if (nameExists) {
				this.errorMessage = `参与者 "${this.currentParticipant.name.trim()}" 已存在`
				return
			}

			const newParticipant = {
				name: this.currentParticipant.name.trim(),
				courtFee: this.currentParticipant.courtFee === '' ? 0 : Number(this.currentParticipant.courtFee),
				shuttleFee: this.currentParticipant.shuttleFee === '' ? 0 : Number(this.currentParticipant.shuttleFee)
			}

			this.participants.push(newParticipant)

			// Reset current participant and close modal
			this.currentParticipant = {
				name: '',
				courtFee: '',
				shuttleFee: ''
			}
			this.errorMessage = ''
			this.showAddModal = false
		},
		validateCurrentFee(feeType) {
			const value = this.currentParticipant[feeType]
			if (value === '') {
				this.currentParticipant[feeType] = ''
				this.errorMessage = ''
				return true
			}

			const fee = Number(value)
			if (isNaN(fee)) {
				this.errorMessage = '请输入有效的数字金额'
				return false
			}

			if (fee < 0) {
				this.errorMessage = '费用金额不能为负数'
				return false
			}

			if (fee > 10000) {
				this.errorMessage = '费用金额似乎过大，请检查是否输入正确'
				return false
			}

			this.errorMessage = ''
			return true
		},
		validateCurrentFee(feeType) {
			const value = this.currentParticipant[feeType]
			if (value === '') {
				this.currentParticipant[feeType] = ''
				this.errorMessage = ''
				return true
			}

			const fee = Number(value)
			if (isNaN(fee)) {
				this.errorMessage = '请输入有效的数字金额'
				return false
			}

			if (fee < 0) {
				this.errorMessage = '费用金额不能为负数'
				return false
			}

			if (fee > 10000) {
				this.errorMessage = '费用金额似乎过大，请检查是否输入正确'
				return false
			}

			this.errorMessage = ''
			return true
		},
		validateFee(event, index, feeType) {
			const value = event.target.value
			if (value === '') {
				this.participants[index][feeType] = ''
				this.errorMessage = ''
				return true
			}

			const fee = Number(value)
			if (isNaN(fee)) {
				this.errorMessage = '请输入有效的数字金额'
				this.participants[index][feeType] = ''
				return false
			}

			if (fee < 0) {
				this.errorMessage = '费用金额不能为负数'
				this.participants[index][feeType] = ''
				return false
			}

			if (fee > 10000) {
				this.errorMessage = '费用金额似乎过大，请检查是否输入正确'
				this.participants[index][feeType] = ''
				return false
			}

			this.participants[index][feeType] = Number(fee.toFixed(2))
			this.errorMessage = ''
			return true
		},
		validateParticipantName(event, currentIndex) {
			const newName = event.target.value.trim()
			if (!newName) {
				this.errorMessage = ''
				this.hasError = false
				return true
			}

			const duplicateIndex = this.participants.findIndex((p, index) =>
				index !== currentIndex && p.name.trim().toLowerCase() === newName.toLowerCase()
			)

			if (duplicateIndex !== -1) {
				this.errorMessage = `提示：参与者 "${newName}" 已存在，请使用其他名字`
				this.hasError = true
				return false
			}

			this.errorMessage = ''
			this.hasError = false
			return true
		},
		handleCurrentParticipantName(event) {
			const newName = event.target.value.trim()
			if (!newName) {
				this.errorMessage = ''
				return
			}

			const exists = this.participants.some(p =>
				p.name.trim().toLowerCase() === newName.toLowerCase()
			)

			if (exists) {
				this.errorMessage = `提示：参与者 "${newName}" 已存在，请使用其他名字`
			} else {
				this.errorMessage = ''
			}
		},
		removeParticipant(index) {
			if (index >= 0 && index < this.participants.length) {
				// 保存要删除的参与者信息，以便需要恢复时使用
				const lastParticipant = { ...this.participants[index] };
				const lastSelectedParticipants = this.timePeriods.map(period => period.selectedParticipants[index]);
				const lastShuttleFeeHalved = this.timePeriods.map(period => period.shuttleFeeHalved[index]);

				// 检查该参与者是否在任何时间段中被选中
				const isParticipantInPeriods = this.timePeriods.some(period =>
					period.selectedParticipants[index]
				);


				if (isParticipantInPeriods && this.settlementType === 'detailed') {
					uni.showModal({
						title: '无法删除',
						content: `参与者"${this.participants[index].name}"已添加到时间段中，请先移除相关时间段的参与记录后再删除。`,
						showCancel: false,
						confirmText: '我知道了',
						confirmColor: '#007AFF'
					});
					return;
				}

				// 如果参与者未被添加到时间段或不是详细计算模式，则可以直接删除
				this.participants.splice(index, 1);
				// Update arrays in all time periods
				this.timePeriods.forEach(period => {
					period.selectedParticipants.splice(index, 1);
					period.shuttleFeeHalved.splice(index, 1);
				});

				// ... existing code ...
				// 如果删除后没有参与者了，且在详细模式下有时间段配置
				if (this.participants.length === 0 && this.settlementType === 'detailed' && this.timePeriods.length > 0) {
					uni.showModal({
						title: '提示',
						content: '删除所有参与者后，之前配置的时间段将失效。是否继续？',
						showCancel: true,
						cancelText: '取消',
						confirmText: '继续',
						success: (res) => {
							if (res.confirm) {
								this.timePeriods = []; // 清空时间段
							} else {
								// 如果用户取消，则恢复刚才删除的参与者
								this.participants.splice(index, 0, lastParticipant);
								// 恢复时间段中的相关数组
								this.timePeriods.forEach(period => {
									period.selectedParticipants.splice(index, 0, lastSelectedParticipants[periodIndex]);
									period.shuttleFeeHalved.splice(index, 0, lastShuttleFeeHalved[periodIndex]);
								});
							}
						}
					});
					return;
				}
				// ... existing code ...

				this.errorMessage = ''; // Clear error message when removing participant
			}
		},

		// Time period management methods
		showAddPeriod() {
			if (this.participants.length === 0) {
				uni.showModal({
					title: '提示',
					content: '请先添加参与者',
					showCancel: false,
					confirmText: '我知道了',
					confirmColor: '#007AFF'
				});
				return;
			}

			this.showAddPeriodModal = true;
			this.currentPeriod = {
				courtFee: '',
				shuttleFee: ''
			};
			this.errorMessage = '';
		},

		cancelAddPeriod() {
			this.showAddPeriodModal = false
			this.currentPeriod = {
				courtFee: '',
				shuttleFee: ''
			}
			this.errorMessage = ''
		},

		validateCurrentPeriodFee(feeType) {
			const value = this.currentPeriod[feeType]
			if (value === '') {
				this.currentPeriod[feeType] = ''
				this.errorMessage = ''
				return true
			}

			const fee = Number(value)
			if (isNaN(fee)) {
				this.errorMessage = '请输入有效的数字金额'
				return false
			}

			if (fee < 0) {
				this.errorMessage = '费用金额不能为负数'
				return false
			}

			if (fee > 10000) {
				this.errorMessage = '费用金额似乎过大，请检查是否输入正确'
				return false
			}

			this.errorMessage = ''
			return true
		},

		addPeriod() {
			if (!this.canAddPeriod) {
				return
			}

			const periodIndex = this.timePeriods.length + 1
			const newPeriod = {
				name: this.currentPeriod.name || `时间段 ${periodIndex}`,
				courtFee: this.currentPeriod.courtFee === '' ? 0 : Number(this.currentPeriod.courtFee),
				shuttleFee: this.currentPeriod.shuttleFee === '' ? 0 : Number(this.currentPeriod.shuttleFee),
				selectedParticipants: new Array(this.participants.length).fill(false),
				shuttleFeeHalved: new Array(this.participants.length).fill(false)
			}

			this.timePeriods.push(newPeriod)

			// Reset current period and close modal
			this.currentPeriod = {
				name: '',
				courtFee: '',
				shuttleFee: ''
			}
			this.errorMessage = ''
			this.showAddPeriodModal = false
		},

		removePeriod(index) {
			this.timePeriods.splice(index, 1)
		},

		toggleParticipant(periodIndex, participantIndex) {
			this.timePeriods[periodIndex].selectedParticipants[participantIndex] =
				!this.timePeriods[periodIndex].selectedParticipants[participantIndex]
		},

		toggleShuttleFeeHalved(periodIndex, participantIndex) {
			this.timePeriods[periodIndex].shuttleFeeHalved[participantIndex] =
				!this.timePeriods[periodIndex].shuttleFeeHalved[participantIndex]
		},

		handleSettlementTypeChange(e) {
			this.settlementType = e.detail.value;
		},

		validateAndSettle() {
			const totalPaid = this.totalPaidAmount;
			const totalCost = this.totalCost;

			if (this.settlementType === 'simple') {
				// Simple settlement calculation
				const totalParticipants = this.participants.length;
				if (totalParticipants === 0) return;

				const summary = {};
				let totalCourtFee = 0;
				let totalShuttleFee = 0;

				// Calculate total fees
				this.participants.forEach(participant => {
					totalCourtFee += Number(participant.courtFee || 0);
					totalShuttleFee += Number(participant.shuttleFee || 0);
				});

				// Calculate total shares for shuttle fee
				let totalShuttleShares = this.participants.reduce((sum, _, index) => {
					return sum + (this.simpleShuttleFeeHalved[index] ? 0.5 : 1);
				}, 0);

				// Calculate per person shares
				const perPersonCourtFee = totalCourtFee / totalParticipants;
				const baseShuttleFeeShare = totalShuttleFee / totalShuttleShares;

				// Calculate settlement for each participant
				this.participants.forEach((participant, index) => {
					if (participant.name) {
						const paidCourtFee = Number(participant.courtFee || 0);
						const paidShuttleFee = Number(participant.shuttleFee || 0);
						const shuttleFeeShare = baseShuttleFeeShare * (this.simpleShuttleFeeHalved[index] ? 0.5 : 1);

						summary[participant.name] = {
							courtFee: Number(paidCourtFee.toFixed(2)),
							shuttleFee: Number(paidShuttleFee.toFixed(2)),
							paid: Number((paidCourtFee + paidShuttleFee).toFixed(2)),
							shouldPay: Number((perPersonCourtFee + shuttleFeeShare).toFixed(2)),
							balance: Number(((paidCourtFee + paidShuttleFee) - (perPersonCourtFee + shuttleFeeShare)).toFixed(2))
						};
					}
				});

				// Navigate to settlement page with data
				const navigationData = {
					settlementResults: summary,
					totalCourtFee: totalCourtFee,
					totalShuttleFee: totalShuttleFee,
					totalCost: totalCourtFee + totalShuttleFee,
					totalPaidAmount: totalCourtFee + totalShuttleFee,
					remarks: this.remarks
				};

				uni.navigateTo({
					url: '/pages/settlement/settlement?data=' + encodeURIComponent(JSON.stringify(navigationData))
				});

				this.errorMessage = '';
				return;
			}

			if (totalPaid !== totalCost) {
				const diff = Math.abs(totalPaid - totalCost).toFixed(2)
				const message = totalPaid > totalCost
					? `垫付总额超出活动费用 ¥${diff}`
					: `垫付总额少于活动费用 ¥${diff}`

				uni.showModal({
					title: '费用不一致',
					content: `${message}，请检查垫付金额`,
					showCancel: true,
					cancelText: '继续编辑',
					confirmText: '我知道了',
					success: (res) => {
						if (res.confirm) {
							this.errorMessage = message + '，请检查垫付金额'
						}
					}
				})
				return
			}

			// Calculate settlement results
			const summary = {}

			this.participants.forEach((participant, participantIndex) => {
				if (participant.name) {
					summary[participant.name] = {
						courtFee: Number(Number(participant.courtFee || 0).toFixed(2)),
						shuttleFee: Number(Number(participant.shuttleFee || 0).toFixed(2)),
						paid: Number((Number(participant.courtFee || 0) + Number(participant.shuttleFee || 0)).toFixed(2)),
						shouldPay: 0,
						balance: 0
					}

					// Calculate share in each time period
					this.timePeriods.forEach(period => {
						if (period.selectedParticipants[participantIndex]) {
							const participantCount = period.selectedParticipants.filter(Boolean).length
							if (participantCount > 0) {
								// Court fee is always evenly split
								const courtFeeShare = Number((Number(period.courtFee || 0) / participantCount).toFixed(2))

								// Calculate shuttle fee share with halving logic
								let shuttleFeeBase = Number(period.shuttleFee || 0)
								let totalShares = 0

								// First calculate total shares considering halved fees
								period.selectedParticipants.forEach((isSelected, idx) => {
									if (isSelected) {
										totalShares += period.shuttleFeeHalved[idx] ? 0.5 : 1
									}
								})

								// Calculate this participant's shuttle fee share
								let shuttleFeeShare = 0
								if (totalShares > 0) {
									shuttleFeeShare = Number(((shuttleFeeBase / totalShares) *
										(period.shuttleFeeHalved[participantIndex] ? 0.5 : 1)).toFixed(2))
								}

								summary[participant.name].shouldPay += courtFeeShare + shuttleFeeShare
							}
						}
					})

					// Calculate final balance with two decimal places
					summary[participant.name].shouldPay = Number(summary[participant.name].shouldPay.toFixed(2))
					summary[participant.name].balance = Number(
						(summary[participant.name].paid - summary[participant.name].shouldPay).toFixed(2)
					)
				}
			})

			// Navigate to settlement page with data
			const navigationData = {
				settlementResults: summary,
				totalCourtFee: Number(this.totalCourtFee.toFixed(2)),
				totalShuttleFee: Number(this.totalShuttleFee.toFixed(2)),
				totalCost: Number(this.totalCost.toFixed(2)),
				totalPaidAmount: Number(this.totalPaidAmount.toFixed(2)),
				remarks: this.remarks
			}

			uni.navigateTo({
				url: '/pages/settlement/settlement?data=' + encodeURIComponent(JSON.stringify(navigationData))
			})

			this.errorMessage = ''
		},

		validatePeriodFee(event, periodIndex, feeType) {
			const value = event.target.value
			if (value === '') {
				this.timePeriods[periodIndex][feeType] = ''
				return
			}

			const fee = Number(value)
			if (isNaN(fee) || fee < 0) {
				this.errorMessage = '费用必须是大于或等于0的数字'
				this.timePeriods[periodIndex][feeType] = ''
				return
			}

			this.timePeriods[periodIndex][feeType] = fee
			this.errorMessage = ''
		},

		// Add share functionality
		onShareAppMessage(res) {
			return {
				title: '羽毛球费用结算助手',
				path: '/pages/index/index',
				summary: '一起来使用羽毛球费用结算助手，轻松计算场地费和球费！',
				imageUrl: '/static/share-image.png',
				success(res) {
					uni.showToast({
						title: '分享成功',
						icon: 'success'
					});
				},
				fail(err) {
					uni.showToast({
						title: '分享失败',
						icon: 'error'
					});
				}
			}
		}
	}
}
</script>

<style>
.container {
	padding: 20rpx;
}

.calculator-form {
	background-color: #fff;
	border-radius: 10rpx;
	padding: 20rpx;
}

.form-title {
	font-size: 36rpx;
	font-weight: bold;
	text-align: center;
	margin-bottom: 30rpx;
}

.section {
	margin-bottom: 30rpx;
}

.section-title {
	font-size: 32rpx;
	font-weight: bold;
	margin-bottom: 20rpx;
}

.participants-list {
	display: flex;
	flex-direction: column;
	gap: 20rpx;
}

.participant-item {
	display: flex;
	gap: 10rpx;
	align-items: center;
	margin-bottom: 10rpx;
	padding: 10rpx;
	background-color: #f8f8f8;
	border-radius: 4rpx;
}

.name-input {
	flex: 2;
	border: 1px solid #ddd;
	padding: 10rpx;
	border-radius: 4rpx;
}

.payment-inputs {
	flex: 3;
	display: flex;
	gap: 10rpx;
}

.payment-input {
	flex: 1;
	border: 1px solid #ddd;
	padding: 10rpx;
	border-radius: 4rpx;
}

.add-btn {
	background-color: #007AFF;
	color: #fff;
	border: none;
	padding: 10rpx 20rpx;
	border-radius: 4rpx;
	margin-top: 20rpx;
}

.remove-btn {
	background-color: #FF3B30;
	color: #fff;
	border: none;
	padding: 5rpx 10rpx;
	border-radius: 4rpx;
	font-size: 24rpx;
	transition: background-color 0.3s;
}

.remove-btn:hover {
	background-color: #c72c2c;
}

.summary-section {
	background-color: #f8f8f8;
	padding: 20rpx;
	border-radius: 8rpx;
	margin-top: 30rpx;
}

.summary-content {
	display: flex;
	flex-direction: column;
	gap: 10rpx;
}

.participants-summary {
	margin-top: 20rpx;
	display: flex;
	flex-direction: column;
	gap: 10rpx;
}

.participant-summary {
	background-color: #fff;
	padding: 15rpx;
	border-radius: 4rpx;
	margin-bottom: 10rpx;
}

.error-message {
	color: #FF3B30;
	font-size: 28rpx;
	margin-bottom: 20rpx;
	padding: 10rpx;
	background-color: #FFE5E5;
	border-radius: 4rpx;
	transition: all 0.3s ease;
}

.add-btn-disabled {
	background-color: #cccccc !important;
	cursor: not-allowed;
}

.add-participant-btn {
	display: flex;
	align-items: center;
	justify-content: center;
	width: 100%;
	padding: 20rpx;
	background-color: #f8f8f8;
	border: 2rpx dashed #007AFF;
	border-radius: 8rpx;
	color: #007AFF;
	font-size: 28rpx;
	margin-top: 20rpx;
}

.add-icon {
	font-size: 32rpx;
	margin-right: 10rpx;
}

.modal-overlay {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.5);
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 1000;
}

.modal-content {
	width: 80%;
	background-color: #fff;
	border-radius: 8rpx;
	padding: 30rpx;
}

.modal-header {
	margin-bottom: 30rpx;
}

.modal-title {
	font-size: 32rpx;
	font-weight: bold;
}

.participant-form {
	display: flex;
	flex-direction: column;
	gap: 20rpx;
	margin-bottom: 30rpx;
}

.modal-input {
	border: 1px solid #ddd;
	padding: 15rpx;
	border-radius: 4rpx;
}

.modal-footer {
	display: flex;
	justify-content: flex-end;
	gap: 20rpx;
}

.modal-btn {
	padding: 15rpx 30rpx;
	border-radius: 4rpx;
	font-size: 28rpx;
}

.cancel-btn {
	background-color: #f5f5f5;
	color: #666;
}

.confirm-btn {
	background-color: #007AFF;
	color: #fff;
}

.btn-disabled {
	background-color: #cccccc !important;
	cursor: not-allowed;
}

.settlement-type {
	margin-bottom: 20rpx;
}

.settlement-radio-group {
	display: flex;
	gap: 30rpx;
}

.radio-label {
	display: flex;
	align-items: center;
	gap: 8rpx;
	font-size: 28rpx;
}

.settle-btn {
	background-color: #34C759;
	color: #fff;
	border: none;
	padding: 20rpx;
	border-radius: 8rpx;
	width: 100%;
	font-size: 32rpx;
	margin-top: 10rpx;
}

.settle-btn-disabled {
	background-color: #cccccc !important;
	cursor: not-allowed;
}

.settlement-section {
	background-color: #f8f8f8;
	padding: 20rpx;
	border-radius: 8rpx;
	margin-top: 30rpx;
}

.settlement-results {
	margin-top: 20rpx;
	display: flex;
	flex-direction: column;
	gap: 10rpx;
}

.participant-summary {
	background-color: #fff;
	padding: 15rpx;
	border-radius: 4rpx;
	margin-bottom: 10rpx;
}

.payment-input::placeholder {
	color: #999;
	font-size: 24rpx;
}

.name-input::placeholder {
	color: #999;
}

.time-period-item {
	background-color: #f5f5f5;
	padding: 20rpx;
	border-radius: 8rpx;
	margin-bottom: 20rpx;
}

.period-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 10rpx;
}

.period-title {
	font-weight: bold;
}

.period-fees {
	display: flex;
	gap: 10rpx;
	margin-bottom: 10rpx;
}

.fee-input {
	flex: 1;
	border: 1px solid #ddd;
	padding: 10rpx;
	border-radius: 4rpx;
}

.period-participants {
	display: flex;
	flex-wrap: wrap;
	gap: 10rpx;
	background-color: #fff;
	padding: 10rpx;
	border-radius: 4rpx;
}

.participant-checkbox {
	display: flex;
	align-items: center;
	gap: 5rpx;
	padding: 5rpx 10rpx;
}

.participant-control {
	display: flex;
	flex-direction: column;
	align-items: flex-start;
	background-color: #ffffff;
	padding: 8rpx 12rpx;
	border-radius: 6rpx;
	box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
}

.participant-main-checkbox {
	display: flex;
	align-items: center;
	gap: 8rpx;
}

.half-fee-switch {
	display: flex;
	align-items: center;
	margin-left: 20rpx;
	margin-top: 4rpx;
}

.switch-label {
	font-size: 24rpx;
	color: #666;
	margin-left: 8rpx;
}

.column-labels {
	display: flex;
	gap: 10rpx;
	align-items: center;
	padding: 10rpx;
	margin-bottom: 10rpx;
	font-size: 24rpx;
	color: #666;
	border-bottom: 1px solid #eee;
}

.name-label {
	flex: 2;
	padding: 0 10rpx;
}

.payment-labels {
	flex: 3;
	display: flex;
	gap: 10rpx;
}

.payment-label {
	flex: 1;
	text-align: center;
}

.action-label {
	width: 80rpx;
	text-align: center;
}

.period-column-labels {
	display: flex;
	gap: 10rpx;
	align-items: center;
	padding: 10rpx;
	margin-bottom: 10rpx;
	font-size: 24rpx;
	color: #666;
	border-bottom: 1px solid #eee;
}

.period-number-label {
	width: 120rpx;
	padding: 0 10rpx;
}

.period-fee-labels {
	flex: 1;
	display: flex;
	gap: 10rpx;
}

.period-fee-label {
	flex: 1;
	text-align: center;
}

.period-action-label {
	width: 80rpx;
	text-align: center;
}

.settlement-info {
	margin-top: 16rpx;
	padding: 16rpx;
	background-color: #f8f8f8;
	border-radius: 8rpx;
	display: flex;
	align-items: center;
	gap: 12rpx;
}

.info-icon {
	color: #007AFF;
	font-size: 28rpx;
}

.info-text {
	color: #666;
	font-size: 26rpx;
	line-height: 1.4;
}

.simple-fee-controls {
	margin: 20rpx 0;
	padding: 20rpx;
	background-color: #f8f8f8;
	border-radius: 8rpx;
}

.simple-fee-title {
	font-size: 28rpx;
	color: #333;
	margin-bottom: 16rpx;
	display: block;
}

.simple-participants-list {
	display: flex;
	flex-wrap: wrap;
	gap: 16rpx;
}

.simple-participant-item {
	display: flex;
	align-items: center;
	gap: 8rpx;
	background-color: #fff;
	padding: 8rpx 12rpx;
	border-radius: 6rpx;
	box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
}

.simple-participant-name {
	font-size: 26rpx;
	color: #333;
}

.remarks-section {
	margin-top: 20rpx;
	width: 100%;
}

.remarks-label {
	display: block;
	font-size: 28rpx;
	color: #666;
	margin-bottom: 8rpx;
}

.remarks-input {
	width: 95%;
	height: 50rpx;
	padding: 16rpx;
	border: 1px solid #ddd;
	border-radius: 8rpx;
	font-size: 28rpx;
	background-color: #fff;
}
</style>
